package com.example.test0.Controller;

import com.example.test0.mapper.UserMapper;
import com.example.test0.model.RestBean;
import com.example.test0.model.User;
import com.example.test0.service.UserService;
import com.google.gson.Gson;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public String login() {
        return "login/login";
    }

    @PostMapping("/login")
    @ResponseBody
    public String loginTest(User user, Model model, HttpServletRequest request) {
        System.out.println("username: " + user.getUsername() + " password: " + user.getPassword());

        RestBean restBean = new RestBean();
        String username = user.getUsername();
        String password = user.getPassword();

        HttpSession session = request.getSession();
        String test_str1 = (String) request.getSession().getAttribute("user");
        String test_str2 = (String) request.getSession().getAttribute("username");
        System.out.println(test_str1 + "   " + test_str2);

        String ret = null;
        if (username.isEmpty()) {
//            model.addAttribute("msg","登录请输入用户名！");
            restBean = new RestBean("false", "用户名不能为空");
        } else {
            User objectuser = userService.FindByUser(user);
            if (objectuser == null) {
                restBean = new RestBean("false", "账号或密码错误");
            } else {
                restBean = new RestBean("true", "登录成功");
                if (objectuser.getPower() == 3) {
                    session.setAttribute("user", "admin");
                    session.setAttribute("username", username);
                    session.setAttribute("userid", objectuser.getId());
                } else if (objectuser.getPower() == 2) {
                    session.setAttribute("user", "user");
                    session.setAttribute("username", username);
                    session.setAttribute("userid", objectuser.getId());
                }
            }
        }
        ret = new Gson().toJson(restBean);
        return ret;
    }

}
